package cn.bocweb.spinning.view.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Chronometer;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bocweb.spinning.R;
import cn.bocweb.spinning.model.Bean.ErrorBean;
import cn.bocweb.spinning.model.Bean.FinishExamBean;
import cn.bocweb.spinning.model.Bean.FinishExamDetailBean;
import cn.bocweb.spinning.model.Bean.StartExamBean;
import cn.bocweb.spinning.model.Bean.UserBean;
import cn.bocweb.spinning.presenter.Imp.UserPresenterImp;
import cn.bocweb.spinning.presenter.UserPresenter;
import cn.bocweb.spinning.util.Constant;
import cn.bocweb.spinning.util.DeviceUtil;
import cn.bocweb.spinning.view.adapter.TestAdapter;
import cn.bocweb.spinning.view.adapter.TestListAdapter;
import cn.bocweb.spinning.view.common.BaseActivity;
import cn.bocweb.spinning.view.common.ReportSecondService;
import cn.bocweb.spinning.view.common.TimeTick;
import cn.bocweb.spinning.view.common.ZoomOutPageTransformer;
import cn.bocweb.spinning.view.dialog.TestDialog;
import cn.bocweb.spinning.view.dialog.TimeStopDialog;
import cn.bocweb.spinning.view.fragment.ExamQuizFragment;
import cn.bocweb.spinning.view.view.ViewPagerScroll;
import de.greenrobot.event.EventBus;

public class TestActivity extends BaseActivity implements View.OnClickListener, TestDialog.OnClickListener {

    TestAdapter testAdapter;
    TestDialog dialog;
    String testId, userId, libid, title,start_time;
    Double timlimitSecond;
    String isChange = "0", datika = "0", isScroll = "0";
    TestListAdapter testListAdapter;
    Map<Integer, Boolean> testlist;
    Map<Integer, String> selectList;
    List<ExamQuizFragment> fragments;
    PopupWindow popupWindow;
    List<StartExamBean.DataEntity> dataEntities;
    UserPresenter presenter;
    int answerWrong = 0;
    List<Integer> right, wrong, miss;
    TimeTick timeLeft;
    TextView examPopupRight;
    TextView examPopupWrong;
    TextView examPopupMiss;
    TimeStopDialog timeStopDialog;
    boolean isListOpen, isFirstMatch, isSecondTest;
    String endTime;
    String testTimelimit;
    long time2;
    boolean isEx;
    TextView examPopupDo;
    Timer timerSubmit;
    int timeSubmit = 3;
    int type1, type2, type3, score, pos = 0;
    String start_timeline;
    String detail;
    long timelimit;
    long end_time;
    String second_test_id;
    String spend_time;
    String datenow,handletime;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.viewPager)
    ViewPagerScroll viewPager;
    @Bind(R.id.btn_finish_test)
    LinearLayout btnFinishTest;
    @Bind(R.id.time_limited)
    TextView timeLimited;
    @Bind(R.id.test_btn_test_list)
    LinearLayout testBtnTestList;
    @Bind(R.id.exam_quiz_total)
    TextView examQuizTotal;
    @Bind(R.id.exam_quiz_writed)
    TextView examQuizWrited;
    @Bind(R.id.exam_quiz_wrong)
    TextView examQuizWrong;
    @Bind(R.id.space_line)
    TextView space_line;
    @Bind(R.id.exam_time_limit)
    Chronometer examTimeLimit;
    @Bind(R.id.test_btn_time)
    LinearLayout testBtnTime;
    @Bind(R.id.wrong_layout)
    LinearLayout mWrongLayout;
    @Bind(R.id.test_main)
    LinearLayout mTestMain;
    @Bind(R.id.prev_quiz)
    LinearLayout prev_quiz;
    @Bind(R.id.next_quiz)
    LinearLayout next_quiz;
    private int lastValue = -1;
    private boolean isSmallToBig = true;
    private boolean isBigToSmall = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);

        start_timeline = String.valueOf(System.currentTimeMillis() / 1000);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);

        presenter = new UserPresenterImp();
        selectList = new HashMap<>();
        timerSubmit = new Timer();
        timeStopDialog = new TimeStopDialog(this);
        timeStopDialog.setOnFinishListener(new TimeStopDialog.OnFinishListener() {
            @Override
            public void click() {
                submitTest();
            }
        });
        datenow = String.valueOf(System.currentTimeMillis() / 1000L);

        initClickBtn();
        initViewPager();
        initIntent();
        initPopupWindow();
        initToolbar();
        initTimeTick();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        DeviceUtil.Log("会调用");
        String limit = timeLimited.getText().toString();
        int aaa = 0;
        int count;

        long endtime = end_time - System.currentTimeMillis();

        if (endtime <= 0) {
            timeStopDialog.show();
            timerSubmit.schedule(new TimerTask() {
                @Override
                public void run() {
                    timeSubmit--;
                    submitTest();
                    timeStopDialog.dismiss();
                }
            }, 3000);
        } else {
            timeLeft = new TimeTick(endtime, 1000, timeLimited);
            dialog.setTimeTick(timeLeft);
            timeLeft.setOnFinishListener(new TimeTick.OnFinishListener() {
                @Override
                public void onFinish(long time) {
                    time2 = time;
                    timeStopDialog.show();
                    if (dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    timerSubmit.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            timeSubmit--;
                            submitTest();
                            timeStopDialog.dismiss();
                        }
                    }, 3000);
                }
            });
            timeLeft.start();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
        timeLeft.cancel();
    }

    public void selectRightAnswer(final int page) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                viewPager.setCurrentItem(page);
            }
        });

    }

    private void initIntent() {
        Intent intent = getIntent();
        isSecondTest = intent.getBooleanExtra(Constant.START_EXAM_ISSECONDTEST, false);
        libid = intent.getStringExtra(Constant.START_EXAM_LIBID);
        if (intent.getStringExtra(Constant.TO_REDAY_TEST_TITLE) != null) {
            title = intent.getStringExtra(Constant.TO_REDAY_TEST_TITLE);
        }
        if (intent.getStringExtra(Constant.TO_TEST_TEST_START_TIME) != null) {
            start_time = intent.getStringExtra(Constant.TO_TEST_TEST_START_TIME);
        }
        if (intent.getDoubleExtra(Constant.TO_TEST_TEST_TIMELIMIT, -0.01) != -0.01) {
            timlimitSecond = intent.getDoubleExtra(Constant.TO_TEST_TEST_TIMELIMIT, 20.00);
        }

        if (!isSecondTest) {
            testId = intent.getStringExtra(Constant.START_EXAM_TESTID);
            userId = intent.getStringExtra(Constant.START_EXAM_USERID);
        } else {
            //isChange "0"为不可滑动
            isChange = intent.getStringExtra(Constant.TO_TEST_IS_CHANGE);
            datika = intent.getStringExtra(Constant.TO_TEST_DATIKA);
            isScroll = intent.getStringExtra(Constant.TO_TEST_SCROLLABLE);
            if (Integer.parseInt(isScroll) == 0) {
                viewPager.setScrollable(false);
                prev_quiz.setClickable(false);
                prev_quiz.setVisibility(View.GONE);
                space_line.setVisibility(View.GONE);
            } else {
                viewPager.setScrollable(true);
                prev_quiz.setClickable(true);
            }
            second_test_id = intent.getStringExtra(Constant.TO_TEST_TEST_ID);
            type1 = intent.getIntExtra(Constant.TO_TEST_SELPOINT, 1);
            type2 = intent.getIntExtra(Constant.TO_TEST_JUDGEPOINT, 2);
            type3 = intent.getIntExtra(Constant.TO_TEST_DUOXUANPOINT, 3);
            if (Integer.parseInt(datika) == 0) {
                testBtnTestList.setClickable(false);
            } else {
                testBtnTestList.setClickable(true);
            }

        }
        isFirstMatch = intent.getBooleanExtra(Constant.START_EXAM_ISFIRSTMATCH, false);
        testTimelimit = intent.getStringExtra(Constant.START_EXAM_TIMELIMIT);

        dataEntities.addAll((List<StartExamBean.DataEntity>) intent.getSerializableExtra(Constant.START_EXAM_LIST));
        boolean isMatch = isSecondTest || isFirstMatch;
        dialog = new TestDialog(this, isMatch);

        for (int i = 0; i < dataEntities.size(); i++) {
            fragments.add(new ExamQuizFragment(dataEntities.get(i), i, isSecondTest, isChange));

        }

        if (isSecondTest || isFirstMatch) {
            mWrongLayout.setVisibility(View.GONE);
        }

        if (intent.hasExtra(Constant.START_EXAM_END_TIME)) {
            endTime = intent.getStringExtra(Constant.START_EXAM_END_TIME);
        } else {
            endTime = "";
        }
    }

    private void initTimeTick() {

        final String timeChronometer;


        if (TextUtils.isEmpty(endTime)) {
            timelimit = Long.parseLong(testTimelimit) * 60 * 1000;
            end_time = System.currentTimeMillis() + timelimit;
            timeChronometer = DeviceUtil.getTickInfoForData(timelimit / 1000);
            DeviceUtil.Log(timeChronometer);
        } else {
            timelimit = (long) (timlimitSecond * 60 * 1000);
//            long nowTime = System.currentTimeMillis();
//            long timeOff = timelimit - nowTime;
            end_time = System.currentTimeMillis() + timelimit;
//            if (timeOff >= Long.parseLong(testTimelimit) * 60 * 1000) {
//                isEx = true;
//                timelimit = Long.parseLong(testTimelimit) * 60 * 1000;
//                end_time = System.currentTimeMillis() + timelimit;
//            } else if (timeOff < Long.parseLong(testTimelimit) * 60 * 1000 && timeOff > 0) {
//                timelimit = timeOff;
//                end_time = Long.parseLong(endTime) * 1000;
//            } else {
//                timelimit = 0;
//            }

        }

        timeLeft = new TimeTick(timelimit, 1000, timeLimited);
        dialog.setTimeTick(timeLeft);
        timeLeft.setOnFinishListener(new TimeTick.OnFinishListener() {
            @Override
            public void onFinish(long time) {
                time2 = time;
                timeStopDialog.show();
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
                timerSubmit.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        timeSubmit--;
                        submitTest();
                        timeStopDialog.dismiss();
                    }
                }, 3000);
            }
        });
        timeLeft.start();
    }

    private void initViewPager() {
        fragments = new ArrayList<>();
        dataEntities = new ArrayList<>();
        testAdapter = new TestAdapter(getSupportFragmentManager(), dataEntities, fragments);
        viewPager.setPageTransformer(true, new ZoomOutPageTransformer());
        viewPager.setAdapter(testAdapter);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            int mCurrentPage = 0;
            boolean isLeft = true;
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                if (positionOffset != 0) {
                    mCurrentPage = position;

                    if (lastValue >= positionOffsetPixels) {
                        //右滑
                        isLeft = false;
                    } else if (lastValue < positionOffsetPixels) {
                        //左滑
                        isLeft = true;
                    }
                    setIndiactorView(positionOffset, isLeft);
                }
                lastValue = positionOffsetPixels;

            }

            @Override
            public void onPageSelected(final int position) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        examQuizWrited.setText(String.valueOf(position + 1));

                        for (int i = 0; i < fragments.size(); i++) {
                            if (i == position) {
                                fragments.get(i).setLayoutVisible(true);
                                pos = i;
                                if (isLeft) {
//                                    if (viewPager.getCurrentItem() != (dataEntities.size() - 1) && pos > 0){
//                                        fragments.get(pos - 1).initSelectResult();
//                                    }
                                }
                            } else {
                                fragments.get(i).setLayoutVisible(false);
                            }
                        }
//                        if(isSecondTest) {
//                            prev_quiz.setBackgroundColor(getResources().getColor(R.color.gray));
//                            if  (fragments.size() == pos+1) {
//                                next_quiz.setBackgroundColor(getResources().getColor(R.color.hint));
//                            }
//                        }else {
//                            prev_quiz.setBackgroundColor(getResources().getColor(R.color.hint));
//                            if (pos == 1) {
//                                prev_quiz.setBackgroundColor(getResources().getColor(R.color.gray));
//                            } else if (fragments.size() == pos+1) {
//                                next_quiz.setBackgroundColor(getResources().getColor(R.color.hint));
//                            }
//                        }
                    }
                });
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }

            private void setIndiactorView(float positionOffset, boolean isLeft) {
                //设定滑动的边界，这里设置的滑动到一半
                float radiusOffsetHead = 0.5f;
                //如果滑动小于一半，通过isSmallToBig这个变量来避免多次调用
                // initIndicatorView 方法
                if (positionOffset <= radiusOffsetHead && !isSmallToBig) {

                    isSmallToBig = true;
                    isBigToSmall = false;

                } else if (positionOffset > radiusOffsetHead && !isBigToSmall) {
                    //超过一半。如果是左滑，就-1，如果是右滑，就+1
//                    int currnt  = isLeft ? mCurrentPage + 1 : mCurrentPage - 1;
                    if (isLeft) {
                        fragments.get(mCurrentPage).initSelectResult();
                    }
                    isBigToSmall = true;
                    isSmallToBig = false;
                }
            }
        });

    }

    private void initClickBtn() {

        testBtnTestList.setOnClickListener(this);
        btnFinishTest.setOnClickListener(this);
        testBtnTime.setOnClickListener(this);
        prev_quiz.setOnClickListener(this);
        next_quiz.setOnClickListener(this);
    }

    private void initToolbar() {
        examQuizWrited.setText("1");
        toolbar.setNavigationIcon(R.mipmap.btn_exit);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isLast;
                if (isSecondTest) {
                    isLast = selectList.size() >= dataEntities.size();
                } else {
                    isLast = selectList.size() >= dataEntities.size();
                }
                initDialog(isLast);
            }
        });

    }

    @Override
    public void onBackPressed() {
        boolean isLast;
        if (isSecondTest) {
            isLast = selectList.size() >= pos;
        } else {
            isLast = selectList.size() >= pos;
        }
        initDialog(isLast);
    }

    public void initDialog(boolean isLast) {

        dialog.setOnClickListener(new TestDialog.OnClickListener() {
            @Override
            public void click(View v) {
                v.setClickable(false);
                v.setBackgroundResource(R.drawable.bg_test_unclickable);
                examTimeLimit.stop();
                submitTest();
            }

            @Override
            public void submit() {
                String limit = timeLimited.getText().toString();
                int aaa = 0;
                int count;
                if (limit.length() == 4) {
                    int second = Integer.parseInt(limit.substring(2, 4));
                    int min = Integer.parseInt(limit.substring(0, 1)) * 60;
                    count = min + second;
                } else {
                    int second = Integer.parseInt(limit.substring(3, 5));
                    int min = Integer.parseInt(limit.substring(0, 2)) * 60;
                    count = min + second;
                }
//                timeLeft = new TimeTick((long) (count * 1000), 1000, timeLimited);
//                testResultDialog.setTimeTick(timeLeft);
//                timeLeft.setOnFinishListener(new TimeTick.OnFinishListener() {
//                    @Override
//                    public void onFinish(long time) {
//                        time2 = time;
//                        timeStopDialog.show();
//                        if (testResultDialog.isShowing()) {
//                            testResultDialog.dismiss();
//                        }
////                        if ()
//                        timerSubmit.schedule(new TimerTask() {
//                            @Override
//                            public void run() {
//                                timeSubmit--;
//                                submitTest();
//                                timeStopDialog.dismiss();
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                timeStopDialog.setBtnText(timeSubmit);
//                            }
//                        });
//
//                            }
//                        }, 3000);
//
//                    }
//                });
//                timeLeft.start();
            }
        });
        if (isLast) {
            dialog.setBtnText("继续答题");
        } else {
            dialog.setBtnText("继续答题");
        }
        int a = miss.size();
        for (int j = 0; j < miss.size(); j++) {
            if (miss.get(j) == 1) {
                a--;
            }

        }
        int b = 0;
        for (int j = 0; j < right.size(); j++) {
            if (right.get(j) == 1) {
                b++;
            }

        }
        int c = 0;
        for (int j = 0; j < wrong.size(); j++) {
            if (wrong.get(j) == 1) {
                c++;
            }

        }
        dialog.setRight(String.valueOf(b));
        dialog.setWrong(String.valueOf(c));
        dialog.setMiss(String.valueOf(a));
        dialog.setGo(String.valueOf(testlist.size()));

        dialog.show();
    }

    private void initPopupWindow() {
        testlist = new HashMap<>();
        testListAdapter = new TestListAdapter(this, 0, testlist, isSecondTest | isFirstMatch);

        View view = LayoutInflater.from(this).inflate(R.layout.window_test_list, null);
        GridView gridView_testList = (GridView) view.findViewById(R.id.test_list);
        RelativeLayout btn_hide = (RelativeLayout) view.findViewById(R.id.btn_hide);
        LinearLayout linearLayoutRightWrong = (LinearLayout) view.findViewById(R.id.linearLayout_right_false);
        LinearLayout linearLayoutDo = (LinearLayout) view.findViewById(R.id.linearLayout_do);
        examPopupDo = (TextView) view.findViewById(R.id.exam_popup_do);

        examPopupRight = (TextView) view.findViewById(R.id.exam_popup_right);
        examPopupWrong = (TextView) view.findViewById(R.id.exam_popup_wrong);
        examPopupMiss = (TextView) view.findViewById(R.id.exam_popup_miss);

        if (isFirstMatch | isSecondTest) {
            linearLayoutRightWrong.setVisibility(View.GONE);
            linearLayoutDo.setVisibility(View.VISIBLE);
        } else {
            linearLayoutRightWrong.setVisibility(View.VISIBLE);
            linearLayoutDo.setVisibility(View.GONE);
        }

        btn_hide.setOnClickListener(this);
        gridView_testList.setAdapter(testListAdapter);

        /**
         * 安卓5.0以下有个问题就是用gridview的onItemClickListener监听不到item的监听事件.真他妈的奇怪
         */
        testListAdapter.setOnItemClickListener(new TestListAdapter.OnItemClickListener() {
            @Override
            public void click(int position) {
                selectRightAnswer(position);
                popupWindow.dismiss();
            }
        });

        int screenHeightPx = DeviceUtil.getScreenHeight(this);
        int navigationHeight = DeviceUtil.getStatusBarHeight(this);
        int toolbarHeight = DeviceUtil.getViewHeight(toolbar);

        popupWindow = new PopupWindow(view, ActionBar.LayoutParams.MATCH_PARENT, screenHeightPx - navigationHeight - toolbarHeight);
        popupWindow.setAnimationStyle(R.style.test_list);

        miss = new ArrayList<>();
        right = new ArrayList<>();
        wrong = new ArrayList<>();
        for (int x = 0; x < dataEntities.size(); x++) {
            miss.add(x, 0);
            right.add(x, 0);
            wrong.add(x, 0);
        }
        int a = miss.size();
        for (int j = 0; j < miss.size(); j++) {
            if (miss.get(j) == 1) {
                a--;
            }
        }
        examPopupMiss.setText(String.valueOf(a));
        examQuizTotal.setText(String.valueOf(dataEntities.size()));
        testListAdapter.setSize(fragments.size());
        viewPager.setOffscreenPageLimit(dataEntities.size());
        testAdapter.notifyDataSetChanged();
        testListAdapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_finish_test: {
                fragments.get(pos).initSelectResult();

                boolean isLast;

                if (!isSecondTest) {
                    isLast = selectList.size() >= pos + 1;
                } else {
                    isLast = selectList.size() >= pos + 1;
                }
                initDialog(isLast);
                break;
            }
            case R.id.test_btn_test_list: {

                if (!isListOpen) {
                    testAdapter.notifyDataSetChanged();
                    popupWindow.showAtLocation(viewPager, Gravity.BOTTOM, 0, 0);
                } else {
                    popupWindow.dismiss();
                }
                isListOpen = !isListOpen;
                break;
            }
            case R.id.btn_hide: {
                popupWindow.dismiss();
                break;
            }
            case R.id.prev_quiz: {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (viewPager.getCurrentItem() != 0) {
                            viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
                        } else {
                            DeviceUtil.MyToast(TestActivity.this, "已至第一题");
                        }
                    }
                });
                break;
            }
            case R.id.next_quiz: {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (pos == 1) {
                            fragments.get(0).initSelectResult();
                        }
                        if (viewPager.getCurrentItem() == dataEntities.size() - 1) {
                            DeviceUtil.MyToast(TestActivity.this, "已至最后一题");
                        }
                        if (viewPager.getCurrentItem() != (dataEntities.size() - 1) && isSecondTest) {

                            if (fragments.get(pos).initSelectResult()) {
                                fragments.get(pos).setAllClickable(isChange);
                                viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);

                            } else if (isScroll.equals("1")) {
                                viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
                            } else {
                                DeviceUtil.MyToast(getApplicationContext(), "您还未选择答案");
                            }

                        } else {
                            fragments.get(pos).initSelectResult();
                            viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
                        }

                    }
                });
                break;
            }
            case R.id.test_btn_time: {
////                examTimeLimit.stop();
//                timeStopDialog.setStop(true);
//                timeStopDialog.setNum(String.valueOf(right + wrong));
//                timeStopDialog.setUndo(String.valueOf(miss));
//                timeStopDialog.show();
            }
        }
    }

    public void addQuizCorrect(int position, boolean isCurrent, int type) {
        miss.set(position, 1);
        int a = miss.size();
        for (int j = 0; j < miss.size(); j++) {
            if (miss.get(j) == 1) {
                a--;
            }

        }
        int c = 0;
        for (int j = 0; j < wrong.size(); j++) {
            if (wrong.get(j) == 1) {
                c++;
            }

        }
        examPopupMiss.setText(String.valueOf(a));
        testlist.put(position, isCurrent);
        DeviceUtil.Log("size == " + testlist.size());
        if (isFirstMatch | isSecondTest) {
            examPopupDo.setText(String.valueOf(testlist.size()));
        }
        if (!isCurrent) {
            if (wrong.get(position) != 1) {
                wrong.set(position, 1);
                right.set(position, 0);
                DeviceUtil.Log("wrong == " + wrong);
                examPopupWrong.setText(String.valueOf(wrong.size()));
                answerWrong++;
                examQuizWrong.setText(String.valueOf(answerWrong));
            }
        } else {

            if (right.get(position) != 1) {
                right.set(position, 1);
                wrong.set(position, 0);
                DeviceUtil.Log("right == " + right);
                switch (type) {
                    case 1:
                        score = score + type1;
                        break;
                    case 2:
                        score = score + type2;
                        break;
                    case 3:
                        score = score + type3;
                        break;
                    default:
                        score = score + 2;
                        break;
                }

            }
            int b = 0;
            for (int j = 0; j < right.size(); j++) {
                if (right.get(j) == 1) {
                    b++;
                }

            }
            examPopupRight.setText(String.valueOf(b));
        }
    }

    public boolean isAllAnswer() {
        if (isSecondTest) {
            return testlist.size() == dataEntities.size();
        } else {
            return testlist.size() == dataEntities.size();
        }
    }

    public void addSelectAnswer(int position, String select) {
        selectList.put(position, select);
    }

    @Override
    public void click(View v) {
        Intent intent = new Intent(TestActivity.this, TestResultActivity.class);
        intent.putExtra(Constant.TO_REDAY_TEST_TITLE, title);
        startActivity(intent);
        finish();
    }

    @Override
    public void submit() {

    }

    public void onEventMainThread(FinishExamBean bean) {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
        if (bean.getReturn_code() == 0) {

            if (isSecondTest) {
                UserBean.DataEntity dataEntity = new UserBean.DataEntity();
                dataEntity.readInfoFromLocal(this);
                Intent intent = new Intent(TestActivity.this, ReportSecondService.class);
                intent.putExtra(Constant.TO_REPORT_SECOND_TESTID, bean.getData().getTestid());
                intent.putExtra(Constant.TO_REPORT_SECOND_USERID, dataEntity.getUserid());
                intent.putExtra(Constant.TO_REPORT_SECOND_DETAIL, detail);

                startService(intent);

            }

            Intent intent = new Intent(this, TestResultActivity.class);
//            intent.putExtra(Constant.EXAM_RESULT, bean.getData());
            if (isSecondTest) {
                intent.putExtra(Constant.CHECK_ANSWER_LIBID, second_test_id);
            } else {
                intent.putExtra(Constant.CHECK_ANSWER_LIBID, testId);
            }
//            intent.putExtra(Constant.EXAM_RESULT_LIBID, libid);
//            intent.putExtra(Constant.EXAM_RESULT_SPEND_TIME,  bean.getData().getSpend_time());
            intent.putExtra(Constant.EXAM_RESULT_ISFIRSTMATCH, isFirstMatch);
            intent.putExtra(Constant.EXAM_RESULT_ISSECONDTEST, isSecondTest);
            intent.putExtra(Constant.TO_REDAY_TEST_TITLE, title);
            intent.putExtra(Constant.TO_TEST_RESULT_ANSWER, Constant.TO_TEST_RESULT_ANSWER);
            startActivity(intent);
            finish();
        } else if (bean.getReturn_code() == -201) {
            DeviceUtil.MyToast(this, bean.getMsg());
            finish();
        } else if (bean.getReturn_code() == -205) {
            final Dialog builder = new Dialog(this);
            builder.addContentView(
                    LayoutInflater
                            .from(this)
                            .inflate(R.layout.dialog_test_finish, mTestMain, false),
                    new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            builder.setOnShowListener(new DialogInterface.OnShowListener() {
                @Override
                public void onShow(final DialogInterface dialog) {
                    new Timer().schedule(new TimerTask() {
                        @Override
                        public void run() {
                            dialog.dismiss();
                        }
                    }, 5000);
                }
            });
            builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    Intent intent = new Intent(TestActivity.this, MainActivity.class);
                    startActivity(intent);
                }
            });
            builder.show();
        } else {
            DeviceUtil.MyToast(this, bean.getMsg());
            finish();
        }
    }

    public void onEventMainThread(ErrorBean bean) {
        hideLoading();
        DeviceUtil.MyToast(this, bean.getErrorMsg());
        finish();
    }


    private void submitTest() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                String limit = timeLimited.getText().toString();
                int count;
                if (limit.length() == 4) {
                    int second = Integer.parseInt(limit.substring(2, 4));
                    int min = Integer.parseInt(limit.substring(0, 1)) * 60;
                    count = min + second;
                } else {
                    int second = Integer.parseInt(limit.substring(3, 5));
                    int min = Integer.parseInt(limit.substring(0, 2)) * 60;
                    count = min + second;
                }
                if (TextUtils.isEmpty(endTime)) {
                    count = Integer.parseInt(testTimelimit) * 60 - count;
                } else {
//                    if (isEx) {
//                        count = (int) (timelimit / 1000) - count;
//                    } else {
//                        count = (int) (timelimit / 1000) - count;
//                    }
                    count = (int) (timelimit / 1000) - count;
                }
                spend_time = String.valueOf(count);
                List<FinishExamDetailBean> list = new ArrayList<>();
                for (int i = 0; i < dataEntities.size(); i++) {
                    FinishExamDetailBean bean = new FinishExamDetailBean();
                    String tType = dataEntities.get(i).getTtype();
                    String tId = dataEntities.get(i).getTid();
                    if (testlist.containsKey(i)) {

                        String choose = selectList.get(i);

                        if (testlist.get(i)) {
                            bean.setId(tId);
                            bean.setTtype(tType);
                            bean.setChoose(choose);
                            bean.setIsright("1");
                        } else {
                            bean.setId(tId);
                            bean.setTtype(tType);
                            bean.setChoose(choose);
                            bean.setIsright("0");
                        }
                    } else {
                        bean.setId(tId);
                        bean.setTtype(tType);

                        bean.setChoose("0");
                        bean.setIsright("2");
                    }
                    list.add(bean);
                }
                Gson gson = new Gson();
                detail = gson.toJson(list);

                if (isSecondTest) {
                    handletime = String.valueOf(System.currentTimeMillis() / 1000L);
                    UserBean.DataEntity dataEntity = new UserBean.DataEntity();
                    dataEntity.readInfoFromLocal(TestActivity.this);
                    SharedPreferences sp = getSharedPreferences(Constant.SECOND_UPDATE, Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString(Constant.SECOND_UPDATE_TEST_ID, testId);
                    editor.putString(Constant.SECOND_UPDATE_USER_ID, dataEntity.getUserid());
                    editor.putString(Constant.SECOND_UPDATE_DATA, detail);
                    editor.putString(Constant.SECOND_UPDATE_SPEND_TIME, spend_time);
                    editor.putString(Constant.SECOND_UPDATE_TIMELIMIT, timlimitSecond.toString());
                    editor.putString(Constant.SECOND_UPDATE_SCORE, String.valueOf(score));
                    editor.putString(Constant.SECOND_UPDATE_START_TIME, start_time);
                    editor.putString(Constant.SECOND_UPDATE_DATE_NOW, datenow);
                    editor.putString(Constant.SECOND_UPDATE_HANDLETIME, handletime);
                    editor.putBoolean(Constant.SECOND_UPDATE_SUCCESS, false);
                    editor.apply();
                    presenter.secondHandle1(dataEntity.getUserid(), start_timeline, libid, String.valueOf(score), second_test_id);
                } else {
                    presenter.finishExam(testId, userId, spend_time, detail, libid);
                }
                DeviceUtil.MyToast(TestActivity.this, "正在提交答案,请稍后...");
            }
        });
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        DeviceUtil.MyToast(this, "内存不足");
    }
}
